import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from '@/components/ui/card';
import { Copy, RefreshCw, Code } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import OpenAIClient from '@/lib/llm';
import ReactMarkdown from 'react-markdown';
import rehypeHighlight from 'rehype-highlight';
import 'highlight.js/styles/atom-one-dark.css';
import Editor from '@monaco-editor/react';

const CodeConverter = () => {
  const [sourceLanguage, setSourceLanguage] = useState('java');
  const [targetLanguage, setTargetLanguage] = useState('python');
  const [inputCode, setInputCode] = useState('');
  const [outputCode, setOutputCode] = useState('');
  const [isConverting, setIsConverting] = useState(false);
  const [error, setError] = useState('');

  const languages = [
    { id: 'java', name: 'Java' },
    { id: 'python', name: 'Python' },
    { id: 'javascript', name: 'JavaScript' },
    { id: 'typescript', name: 'TypeScript' },
    { id: 'csharp', name: 'C#' },
    { id: 'cpp', name: 'C++' },
    { id: 'go', name: 'Go' },
    { id: 'ruby', name: 'Ruby' },
    { id: 'php', name: 'PHP' },
    { id: 'swift', name: 'Swift' },
  ];

  const convertCode = async () => {
    if (!inputCode.trim()) {
      setError('请输入要转换的代码');
      return;
    }
    
    setIsConverting(true);
    setError('');
    
    try {
      const openai = new OpenAIClient();
      const prompt = `将以下${languages.find(l => l.id === sourceLanguage)?.name}代码转换为${languages.find(l => l.id === targetLanguage)?.name}代码:\n\n${inputCode}`;
      
      const response = await openai.chat([
        {
          role: 'system',
          content: '你是一个专业的代码转换工具，能够准确地将代码从一种编程语言转换为另一种编程语言。直接生成代码，也不要写``` ```,并且建议使用注释或者注释文档写'
        },
        {
          role: 'user',
          content: prompt
        }
      ], {
        temperature: parseFloat(import.meta.env.VITE_TEMPERATURE) || 0.2
      });
      
      setOutputCode(response);
    } catch (error) {
      console.error('代码转换错误:', error);
      setError(`转换失败: ${error.message}`);
    } finally {
      setIsConverting(false);
    }
  };

  const copyToClipboard = () => {
    navigator.clipboard.writeText(outputCode);
  };

  return (
    <Card className="h-full flex flex-col">
      <CardHeader className="pb-3">
        <div className="flex items-center gap-3">
          <Code className="text-orange-500" size={24} />
          <CardTitle>代码转换器</CardTitle>
        </div>
      </CardHeader>
      <CardContent className="flex-1 grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 左侧输入区域 */}
        <div className="space-y-4">
          <div>
            <label className="block mb-2 text-sm font-medium">源语言</label>
            <Select value={sourceLanguage} onValueChange={setSourceLanguage}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="选择源语言" />
              </SelectTrigger>
              <SelectContent>
                {languages.map((lang) => (
                  <SelectItem key={`source-${lang.id}`} value={lang.id}>
                    {lang.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          
          <div>
            <label className="block mb-2 text-sm font-medium">输入代码</label>
            <div className="min-h-[300px] border rounded-md overflow-hidden">
            <Editor
              height="300px"
              language={sourceLanguage}
              value={inputCode}
              onChange={(value) => setInputCode(value || '')}
              options={{
                minimap: { enabled: false },
                scrollBeyondLastLine: false,
                fontSize: 14,
                wordWrap: 'on',
                automaticLayout: true
              }}
            />
          </div>
          </div>
        </div>
        
        {/* 右侧输出区域 */}
        <div className="space-y-4">
          <div>
            <label className="block mb-2 text-sm font-medium">目标语言</label>
            <Select value={targetLanguage} onValueChange={setTargetLanguage}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="选择目标语言" />
              </SelectTrigger>
              <SelectContent>
                {languages.map((lang) => (
                  <SelectItem key={`target-${lang.id}`} value={lang.id}>
                    {lang.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          
          <div>
            <label className="block mb-2 text-sm font-medium">转换结果</label>
            <div className="relative bg-gray-50 rounded-md overflow-auto max-h-[300px]">
            {error && <div className="text-red-500 p-2">{error}</div>}
            {outputCode ? (
              <div className="prose prose-zinc max-w-none dark:prose-invert min-h-[300px] w-full">
                <ReactMarkdown rehypePlugins={[rehypeHighlight]}>
                  {`\`\`\`${targetLanguage}\n${outputCode}\n\`\`\``}
                </ReactMarkdown>
              </div>
            ) : (
              <div className="p-4 text-gray-500">
                {languages.find(l => l.id === targetLanguage)?.name} 代码将显示在这里
              </div>
            )}
            {outputCode && (
              <Button 
                size="icon" 
                variant="ghost" 
                className="absolute top-2 right-2"
                onClick={copyToClipboard}
              >
                <Copy size={16} />
              </Button>
            )}
          </div>
          </div>
        </div>
      </CardContent>
      <CardFooter>
        <Button 
          onClick={convertCode} 
          className="w-full bg-orange-600 hover:bg-orange-700"
          disabled={isConverting || !inputCode.trim()}
        >
          {isConverting ? (
            <RefreshCw className="mr-2 animate-spin" size={16} />
          ) : (
            <RefreshCw className="mr-2" size={16} />
          )}
          {isConverting ? '转换中...' : '转换代码'}
        </Button>
      </CardFooter>
    </Card>
  );
};

export default CodeConverter;
